package com.csl.smvc.push;

import org.apache.commons.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.SMS;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

/**
 * 推送工具类
 * @author liucs
 *
 */
public class PushUtil {
	private static String masterSecret="7b630f91c1a9c90360860550";
	private static String appKey="2961a11b5606263930068ef1";
	public static Logger log=LoggerFactory.getLogger(PushUtil.class);
	
	public static void pushByAlias(String title,String url,String... alias) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					PushPayload payload=new PushPayload
							.Builder().setPlatform(Platform.all())
							.setAudience(Audience.alias(alias))
							.setNotification(Notification.newBuilder()
									.addPlatformNotification(IosNotification.newBuilder()
										.setAlert(title)
										.addExtra("url", url)
										.build())
									.addPlatformNotification(AndroidNotification.newBuilder()
											.setAlert(title)
											.addExtra("url", url)
											.build())
									.build())
									.build();
				JPushClient jPushClient=new JPushClient(masterSecret, appKey,null,ClientConfig.getInstance());
				jPushClient.sendPush(payload);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	/**
	 * 发短消息测试
	 */
	public static void testSendWithSMS() {
		JPushClient jPushClient=new JPushClient(masterSecret, appKey);
		try {
			SMS sms=SMS.newBuilder()
					.setDelayTime(1000)
					.setTempID(2000)
					.addPara("TEST", 1)
					.build();
			PushResult result=jPushClient.sendAndroidMessageWithAlias("Test SMS", "SMS-content",sms, "alias1");
			log.info("Got result -"+result);
		} catch (APIConnectionException e) {
			log.error("Connection error.Should retry later.",e);
		} catch (APIRequestException e) {
			log.error("Error response from JPush server. Should review and fix it. ", e);
			log.info("HTTP Status: " + e.getStatus());
			log.info("Error Code: " + e.getErrorCode());
			log.info("Error Message: " + e.getErrorMessage());
		}
	}
	//测试
	public static void main(String[] args) {
//		PushUtil.pushByAlias("推送内容头", "http://www.baidu.com", "abc");
		testSendWithSMS();
	}

}
